<div data-title="Device configuration" style="height: 100%;">
  <div class="col-xs-12 main-left-column">
    <div style="margin-top: 5px; ">
      <button class="btn btn-sm btn-success" id="config-save-button"><i class="fa fa-save"></i> Save configuration</button>
      <div class="btn-group btn-group-sm" data-toggle="buttons" style="margin-bottom: 5px; margin-top: 0;">
        <label class="btn btn-default active">
          <i class="fa fa-cog"></i>
          <input type="radio" name="options" id="view1" checked> Simple View
        </label>
        <label class="btn btn-default">
          <i class="fa fa-cogs"></i>
          <input type="radio" name="options" id="view2"> Expert View
        </label>
      </div>
    </div>
    <div class="upcontrol">
      <div id="simple" style="height: 100%;" class="row">

        <div class="col-md-4 col-xs-12" id="section-sntp">
          <div class="x_panel">
            <div class="x_title">SNTP Settings</div>
            <div class="x_content form-horizontal">
              <div class="form-group">
                <label class="col-xs-4 control-label">Enable SNTP</label>
                <div class="col-xs-8"><input type="checkbox" class="form-control" id="sntp.enable"></div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label">SNTP server</label>
                <div class="col-xs-8"><input type="text" class="form-control"
                  id="sntp.server" placeholder="pool.ntp.org"></div>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-4 col-xs-12" id="section-dns-sd">
          <div class="x_panel">
            <div class="x_title">Local Network Discovery</div>
            <div class="x_content form-horizontal">
              <div class="form-group">
                <label class="col-xs-4 control-label">Enable DNS-SD</label>
                <div class="col-xs-8"><input type="checkbox" class="form-control" id="dns_sd.enable"></div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label">Host name</label>
                <div class="col-xs-8"><input type="text" class="form-control"
                  id="dns_sd.host_name" placeholder="my_device"></div>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-4 col-xs-12" id="section-debug">
          <div class="x_panel">
            <div class="x_title">Debug Settings</div>
            <div class="x_content form-horizontal">
              <div class="form-group">
                <label class="col-xs-5 control-label">Hexdump traffic:</label>
                <div class="col-xs-7"><input type="checkbox" class="form-control" id="debug.hexdump"></div>
              </div>
              <div class="form-group">
                <label class="col-xs-5 control-label">Log level:</label>
                <div class="col-xs-7"><input type="text" class="form-control"
                  id="debug.level" placeholder="2"></div>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-6 col-xs-12"  id="section-mqtt">
          <div class="x_panel">
            <div class="x_title">MQTT Settings</div>
            <div class="x_content form-horizontal">
              <div class="form-group">
                <label class="col-xs-4 control-label">Enable MQTT</label>
                <div class="col-xs-8"><input type="checkbox" class="form-control" id="mqtt.enable"></div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label">MQTT server</label>
                <div class="col-xs-8"><input type="text" class="form-control"
                  id="mqtt.server" placeholder="example.com:1883"></div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label">User</label>
                <div class="col-xs-8"><input type="text" class="form-control"
                  id="mqtt.user" placeholder="type user name ..."></div>
              </div>
              <div class="form-group">
                <label class="col-xs-4 control-label">Password</label>
                <div class="col-xs-8"><input type="text" class="form-control"
                  id="mqtt.pass" placeholder="type password ..."></div>
              </div>
            </div>
            <div class="text-muted">
              MQTT device address:
                <span id="mqtt-device-address" class="text-success"></span>
            </div>
            <div class="text-muted">
              <br>If MQTT is enabled, you can copy-paste this address into the
              "device address" field of the connection wizard, and manage
              your device remotely. Note: public MQTT clouds do not protect
              your device from unauthorised access. For security, use
              authenticated MQTT services like AWS IoT, Google IoT core, etc.
            </div>
          </div>
        </div>

        <div class="col-md-6 col-xs-12"  id="section-aws">
          <div class="x_panel">
            <div class="x_title">
              Provision device on AWS IoT
              <div class="pull-right">
                <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-set-up.html">AWS setup page</a>
                |
                <a href="http://docs.aws.amazon.com/iot/latest/developerguide/create-iot-policy.html">AWS policy guide</a>
              </div>
            </div>
            <div class="x_content form-horizontal">

              <div id="aws-cred" class="hidden">
                <div class="text-muted form-group">
                  AWS credentials are missing. Visit AWS setup page, fill in the values
                  and click Save.
                </div>
                <div class="form-group">
                  <label class="col-xs-4 control-label">Access Key ID:</label>
                  <div class="col-xs-8"><input type="text" class="form-control" id="input-awskey"
                    placeholder="type AWS Access Key ID"></div>
                </div>
                <div class="form-group">
                  <label class="col-xs-4 control-label">Secret Access Key:</label>
                  <div class="col-xs-8"><input type="text" class="form-control" id="input-awssecret"
                    placeholder="type AWS Secret Access Key"></div>
                </div>
                <div class="form-group">
                  <button id="aws-cred-button" class="btn btn-success pull-right">
                    <i class="fa fa-save"></i>
                    Save AWS credentials
                  </button>
                </div>
              </div>

              <div id="aws-setup" class="hidden">
                <div class="text-muted form-group">
                  Choose an existing policy, or use mos-default
                  to create a permissive policy automatically.
                </div>                  
                <div class="form-group">
                  <label class="control-label col-xs-4">AWS region:</label>
                  <div class="col-xs-8"><div class="input-group">
                    <span class="input-group-btn">
                      <div class="btn-group dropdown">
                        <button type="button" class="btn btn-default dropdown-toggle"
                          data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                          <span class="caret"></span>
                          <span class="sr-only">Toggle Dropdown</span>
                        </button>
                        <ul class="dropdown-menu" id="dropdown-regions"></ul>
                      </div>
                    </span>
                    <input type="text" class="form-control" id="input-region" placeholder="Choose region ...">
                  </div>
                </div></div>

                <div class="form-group">
                  <label class="control-label col-xs-4">AWS policy:</label>
                  <div class="col-xs-8"><div class="input-group">
                    <span class="input-group-btn">
                      <div class="btn-group dropdown">
                        <button type="button" class="btn btn-default dropdown-toggle"
                          data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                          <span class="caret"></span>
                          <span class="sr-only">Toggle Dropdown</span>
                        </button>
                        <ul class="dropdown-menu" id="dropdown-policies">
                        </ul>
                      </div>
                    </span>
                    <input type="text" class="form-control" id="input-policy" placeholder="Choose policy ...">
                  </div>
                </div></div>
                <div class="form-group">
                  <button id="aws-setup-button" class="btn btn-success pull-right">
                    <i class="fa fa-cloud-upload"></i>
                    Provision with AWS IoT
                  </button>
                </div>
              </div>

            </div>
          </div>
        </div>

      </div>

      <div id="config_editor" class="editor hidden"></div>
    </div>
  </div>
</div>

<script>
  var config_editor = mkeditor('config_editor');
  var loadConfig = function() {
    return $.ajax({url: '/call', data: {method: 'Config.Get'}}).then(function(json) {
      var text = JSON.stringify(json.result, null, '  ');
      config_editor.setValue(text || '', -1);
      config_editor.session.setMode('ace/mode/json');
      addLog('Configuration loaded\n');

      var c = json.result;
      if (c.mqtt) {
        $('#mqtt\\.enable').prop('checked', c.mqtt.enable);
        $('#mqtt\\.server').val(c.mqtt.server || getCookie('mqtt'));
        $('#mqtt\\.user').val(c.mqtt.user || '');
        $('#mqtt\\.pass').val(c.mqtt.pass || '');

        var mqttAddr = c.mqtt.ssl_ca_cert ? 'mqtts://' : 'mqtt://';
        if (c.mqtt.user) mqttAddr += c.mqtt.user + ':' + c.mqtt.pass + '@';
        mqttAddr += c.mqtt.server + '/' + c.device.id;
        $('#mqtt-device-address').text(mqttAddr);
      } else {
        $('#section-mqtt').addClass('hidden');
      }

      if (c.sntp) {
        $('#sntp\\.enable').prop('checked', c.sntp.enable);
        $('#sntp\\.server').val(c.sntp.server || getCookie('sntp'));
      } else {
        $('#section-sntp').addClass('hidden');
      }

      if (c.dns_sd) {
        $('#dns_sd\\.enable').prop('checked', c.dns_sd.enable);
        $('#dns_sd\\.host_name').val(c.dns_sd.host_name || '');
      } else {
        $('#section-dns-sd').addClass('hidden');
      }

      if (c.debug) {
        $('#debug\\.hexdump').prop('checked', c.debug.mg_mgr_hexdump_file == '-');
        $('#debug\\.level').val(c.debug.level || 2);
      } else {
        $('#section-debug').addClass('hidden');
      }

      if (c.aws) {
        $.ajax({url: '/check-aws-credentials'}).then(function(json) {
          var hasAwsCredentials = json.result;
          $('#aws-setup').toggleClass('hidden', !hasAwsCredentials);
          $('#aws-cred').toggleClass('hidden', hasAwsCredentials);
          if (hasAwsCredentials) {
            $.ajax({url: '/regions'}).then(function(json) {
              if (!json.result) return;
              $('#dropdown-regions').empty();
              $.each(json.result, function(i, v) {
                $('<li><a href="#">' + v + '</a></li>').appendTo('#dropdown-regions');
              });
              var region = $('#input-region').val();
              $.ajax({url: '/policies', data: {region: region }}).then(function(json) {
                if (!json.result) return;
                $('#dropdown-policies').empty();
                $.each(json.result, function(i, v) {
                  $('<li><a href="#">' + v + '</a></li>').appendTo('#dropdown-policies');
                });
              });
            });
          }
        });
      } else {
        $('#section-aws').addClass('hidden');
      }

    });
  };
  loadConfig();

  $(document).off('click', '#config-save-button');
  $(document).on('click', '#config-save-button', function() {
    var config = {mqtt: {}, sntp: {}, debug: {}, dns_sd: {}};
    if ($('#view1').is(':checked')) {
      config.mqtt.enable = $('#mqtt\\.enable').is(':checked');
      config.mqtt.server = $('#mqtt\\.server').val();
      config.mqtt.user = $('#mqtt\\.user').val();
      config.mqtt.pass = $('#mqtt\\.pass').val();
      config.sntp.enable = $('#sntp\\.enable').is(':checked');
      config.sntp.server = $('#sntp\\.server').val();
      config.dns_sd.enable = $('#dns_sd\\.enable').is(':checked');
      config.dns_sd.host_name = $('#dns_sd\\.host_name').val();
      config.debug.level = + $('#debug\\.level').val();
      config.debug.mg_mgr_hexdump_file = $('#debug\\.hexdump').is(':checked') ? '-' : '';
    } else {
      var text = config_editor.getValue();
      try {
        config = JSON.parse(text);
      } catch (e) {
        new PNotify({title: 'Error in configuration JSON', type: 'error' });
        return false;
      }
    }

    $.ajax({url: '/call', data: {
      method: 'Config.Set',
      args: JSON.stringify({config: config})}
    }).then(function() {
        return $.ajax({url: '/call', data: {method: 'Config.Save', args: '{"reboot":true}'}});
    }).then(function(json) {
      addLog('Configuration saved\n');
      loadConfig();
    });
  });

  $(document).on('click', '#aws-cred-button', function() {
    var key = $('#input-awskey').val();
    var secret = $('#input-awssecret').val();
    if (!key || !secret) {
      new PNotify({title: 'Invalid AWS IoT credentials', type: 'error'});      
      return false;
    }
    var btn = spin(this);
    $.ajax({url: '/aws-store-creds', global: false, data: {key: key, secret: secret}}).then(function(json) {
      new PNotify({title: 'Saved AWS IoT credentials', type: 'success'});
      loadConfig();
    }).always(function() {
      stopspin(btn);
    });
  });

  $(document).on('click', '#aws-setup-button', function() {
    var policy = $('#input-policy').val();
    var region = $('#input-region').val();
    var btn = spin(this);
    $.ajax({url: '/aws-iot-setup', global: false, data: {region: region, policy: policy}}).then(function(json) {
      new PNotify({title: 'AWS IoT provisioning success', type: 'success'});
      loadConfig();
    }).fail(function(xhr) {
      new PNotify({title: 'AWS IoT provisioning failed: ' + (xhr.responseText || ''), type: 'error'});
    }).always(function() {
      stopspin(btn);
    });
  });

  $(document).off('change', '#view1, #view2');
  $(document).on('change', '#view1, #view2', function() {
    var v1 = $('#view1').is(':checked');
    $('#config_editor').toggleClass('hidden', v1);
    $('#simple').toggleClass('hidden', !v1);
  });
</script>
